package com.tom.demo.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class AsyncTaskConfig {

    /**
     * Spring 默认会查找名为 "taskExecutor" 的 Bean,
     * 如果使用@Async注解的时候，没有显示的指定value="xxx",则默认找 Bean(name=taskExecutor)
     * 如果没有找到配置的Bean的名称是:taskExecutor,那么会走:SimpleAsyncTaskExecutor
     * @return
     */
    @Primary
    @Bean(name = "taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors()); // 核心线程数
        threadPoolTaskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);  // 最大线程数
        threadPoolTaskExecutor.setQueueCapacity(50); // 队列容量
        threadPoolTaskExecutor.setThreadNamePrefix("Default-Async-Task-Thread-Pool");
        // 所有任务结束后关闭线程池
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 队列满时在调用线程执行以避免丢失
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

    /**
     * 异步执行时，也就是加了@Async(value="springAsyncTaskExecutor")注解时候，使用下面这个配置
     * @return
     */

    @Bean(name = "springAsyncTaskExecutor")
    public Executor springTaskExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors()); // 核心线程数
        threadPoolTaskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2); // 最大线程数
        threadPoolTaskExecutor.setQueueCapacity(25); // 队列容量
        threadPoolTaskExecutor.setThreadNamePrefix("<===MY-AsyncTask-Thread-Pool===>");
        // 所有任务结束后关闭线程池
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 队列满时在调用线程执行以避免丢失
        // 初始化
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}

